import React, { Component } from 'react';
import { Space, Select, Card, Tooltip, Statistic, Typography, Modal, message } from "antd";
import { QuestionCircleFilled } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheQueryForm from '@/components/TheQueryForm';
import { exportSheetTable } from '@/utils/exportTable.js';
import { storeAccountPrice, openCommissionList, storeCashFlowCommissionPage, exportStoreCashFlowCommissionPage } from '@/request/storeBackManage/fundsManage/accountManage';
import _ from 'lodash'
import moment from 'moment'
const { Paragraph } = Typography;

class Index extends Component {
  state = {
    options: [],
    columns: [
      {
        title: "申请编号",
        dataIndex: "storeCashFlowCommissionId",
        key: "storeCashFlowCommissionId",
        width:200
      },
      {
        title: "所属商家",
        dataIndex: "storeName",
        key: "storeName",
        width:260
      },
      {
        title: "类型",
        dataIndex: "businessType",
        key: "businessType",
        render: (text) => {
          return text === 2 && '提现'
        }
      },
      {
        title: "金额(元)",
        dataIndex: "price",
        key: "price",
        render: (text) => {
          return <React.$Price price={text} />
        }
      },
      {
        title: "申请状态",
        dataIndex: "auditState",
        key: "auditState",
        render: (text, record) => {
          let label = ''
          switch (text) {
            case 0:
              label = '待审核'
              break
            case 1:
              label = '通过'
              break
            case 2:
              label = '通过 '
              break
            case 3:
              label = (
                <Space>
                  <span>驳回</span>
                  <Tooltip title={record.rejectReason}>
                    <QuestionCircleFilled />
                  </Tooltip>
                </Space>
              )
              break
          }
          return label
        }
      },
      {
        title: "申请时间",
        dataIndex: "applyTime",
        key: "applyTime",
        width:200
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark",
        width:200
      },
      {
        title: "提现状态",
        dataIndex: "payState",
        key: "payState",
        render: (text, record) => {
          let label = ''
          switch (text) {
            case 0:
              label = '提现中'
              break
            case 1:
              label = '成功'
              break
            case 2:
              label = <div >
                <span style={{ marginRight: 5 }}>失败</span>
                <Tooltip title={record.failReason}>
                  <QuestionCircleFilled />
                </Tooltip>
              </div>

              break
            default:
              label = '-'
          }
          return label
        }
      },
      {
        title: "流水编号",
        dataIndex: "payCode",
        key: "payCode",
        width:200
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    form_show: true,
    searchOption: [
      {
        field: 'storeCashFlowCommissionId',
        label: '申请编号',
        placeholder: '请输入',
        required: false,
        rules: [],
        type: 'Input',
        defaultValue: ''
      },
      {
        field: 'payCode',
        label: '流水编号',
        placeholder: '请输入',
        required: false,
        rules: [],
        type: 'Input',
        defaultValue: ''
      },
      {
        field: 'auditState',
        label: '申请状态',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'Select',
        options: [
          { value: '', label: '全部' },
          { value: 0, label: '待审核' },
          { value: 1, label: '通过' },
          { value: 3, label: '驳回' }
        ],
        defaultValue: ''
      },
      {
        field: 'payState',
        label: '提现状态',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'Select',
        options: [
          { value: '', label: '全部' },
          { value: 0, label: '提现中' },
          { value: 1, label: '成功' },
          { value: 2, label: '失败' }
        ],
        defaultValue: ''
      },
      { field: 'time', label: '申请时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
    ],
    storeList: [],//选择的商家店铺id
    queryForm: {},
    withdrawPrice: '', //已提现金额
    canWithdrawPrice: '', // 可提现金额
    waitSettledPrice: '',//待结算金额 
    exportLoading: false, //导出loading
  }

  componentDidMount() {
    this.getStoreList()
    this.getAmountSummary()
    this.getStoreDetailsData()
  }
  // 商家店铺下拉列表
  getStoreList = async () => {
    let res = await openCommissionList()
    if (res.code === 0 && res.data) {
      console.log(res.data)
      let arr = []
      arr = res.data.map(item => {
        return {
          label: item.storeName,
          value: item.storeId
        }
      })
      this.setState({ options: arr })
    }
  }
  storeHandleChange = (e) => {
    this.setState({ storeList: e })
    this.getAmountSummary(e)
    this.pageChange(1, 10)
  }
  // 商家账户金额汇总
  getAmountSummary = async (storeId) => {
    let res = await storeAccountPrice({ storeIdList: storeId })
    if (res.code === 0 && res.data) {
      this.setState({
        withdrawPrice: Number(res.data.withdrawPrice || 0).tranFormat(2, -2),
        canWithdrawPrice: Number(res.data.canWithdrawPrice || 0).tranFormat(2, -2),
        waitSettledPrice: Number(res.data.waitSettledPrice || 0).tranFormat(2, -2)
      })
    }
  }
  // 商家资金流水明细
  getStoreDetailsData = async (storeIds, value) => {
    const { pageData, queryForm } = this.state
    let params = { ...pageData, ...queryForm, storeIds, ...value, businessType: 2 }
    if (storeIds && storeIds.length == 0) {
      delete params.storeIds
    }
    let res = await storeCashFlowCommissionPage({ ...params })
    if (res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageNo: res.pageNo,
        pageSize: res.pageSize,
        total: res.totalCount
      })
    }
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => {
      this.getStoreDetailsData(this.state.storeList)
    })
  };
  /**
   * @desc 表格搜索组件重置搜索条件
   * */
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  /**
   * @desc 表格搜索组件搜索
   * */
  onFormSearch(value) {
    if (value && value.hasOwnProperty('time')) {
      value.applyBeginTime = moment(value.time[0]).format('yyyy-MM-DD') + ' 00:00:00'
      value.applyEndTime = moment(value.time[1]).format('yyyy-MM-DD') + ' 23:59:59'
      delete value.time
    }
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      queryForm: { ...value }
    }, () => {
      this.getStoreDetailsData(this.state.storeList, value)
    })
  }
  /**
   * @desc 表格数据导出
   * */
  toExport = async () => {
    const { queryForm } = this.state;
    if (_.isEmpty(queryForm)) {
      Modal.warning({ title: '请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。', });
      return
    }
    this.setState({ exportLoading: true })
    let params = {
      ...queryForm,
      businessType: 2,
      storeIds: this.state.storeList
    }
    if (this.state.storeList && this.state.storeList.length == 0) {
      delete params.storeIds
    }
    let res = await exportStoreCashFlowCommissionPage({ ...params })
    if (res.code === 0) {
      let th_arr = [
        {
          title: '商家资金流水明细',
          prop: '',
          children: [
            {
              title: "申请编号",
              prop: "storeCashFlowCommissionId",
            },
            {
              title: "所属商家",
              prop: "storeName",
            },
            {
              title: "类型",
              prop: "businessType",
            },
            {
              title: "金额(元)",
              prop: "price",
            },
            {
              title: "申请状态",
              prop: "auditState",
            },
            {
              title: "申请时间",
              prop: "applyTime",
            },
            {
              title: "备注",
              prop: "remark",
            },
            {
              title: "提现状态",
              prop: "payState",
            },
            {
              title: "流水编号",
              prop: "payCode",
            },
          ]
        },
      ]
      let tb_arr = []
      res.data.forEach((item, index) => {
        let auditState = ''
        let payState = ''
        //审核状态
        switch (item.auditState) {
          case 0:
            auditState = '待审核'
            break
          case 1:
            auditState = '通过'
            break
          case 2:
            auditState = '通过 '
            break
          case 3:
            auditState = '驳回'
            break
        }
        //提现状态
        switch (item.payState) {
          case 0:
            payState = '提现中'
            break
          case 1:
            payState = '成功'
            break
          case 2:
            payState = '失败 '
            break
          default:
            payState = '-'
        }
        tb_arr.push({
          ...item,
          index: index + 1,
          payState: payState,
          auditState: auditState,
          price: '￥' + (item.price / 100).toFixed(2) || '￥0.00',
          businessType: '提现'
        })
      })
      exportSheetTable({ fileName: '商家资金流水明细', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
    }
    this.setState({ exportLoading: false })
  }

  render() {
    let {
      options,
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      searchOption,
      form_show,
      withdrawPrice,
      canWithdrawPrice,
      waitSettledPrice,
    } = this.state
    return (
      <div className={"p-layout-box commodity-content"}>
        <Paragraph strong style={{ margin: 0 }}>
          <blockquote>商家账户金额汇总</blockquote>
        </Paragraph>
        <Space style={{ marginBottom: 20, paddingLeft: 50 }}>
          <span style={{ fontSize: 14 }}>所属商家：</span>
          <Select
            mode="multiple"
            allowClear
            style={{ width: '280px' }}
            placeholder="全部"
            onChange={this.storeHandleChange}
            options={options}
          />
        </Space>
        <Space align={"center"} size={30}>
          <Card
            style={{ width: 300 }}
            title="已提现金额"
            extra={
              <Tooltip title="所选商家累计提现的金额">
                <QuestionCircleFilled style={{ fontSize: 20 }} />
              </Tooltip>
            }
          >
            <Statistic prefix={"￥"} value={withdrawPrice} />
          </Card>
          <Card
            style={{ width: 300 }}
            title="可提现金额"
            extra={
              <Tooltip title="可提现金额=订单中状态为已结算的实付金额之和 - 已提现金额">
                <QuestionCircleFilled style={{ fontSize: 20 }} />
              </Tooltip>
            }
          >
            <Statistic prefix={"￥"} value={canWithdrawPrice} />
          </Card>
          <Card
            style={{ width: 300 }}
            title="待结算金额"
            extra={
              <Tooltip title="待结算金额=订单中状态为“ 待分享、待发货、待收货、交易完成” 的金额之和">
                <QuestionCircleFilled style={{ fontSize: 20 }} />
              </Tooltip>
            }
          >
            <Statistic prefix={"￥"} value={waitSettledPrice} />
          </Card>
        </Space>
        <Paragraph strong style={{ margin: 0 }}>
          <blockquote>商家资金流水明细</blockquote>
        </Paragraph>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton  haspermi={['storeBack:accountManage:export']} size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
        </TheQueryForm>
        <TheTable
          scroll={{ x: "960", y: '63vh' }}
          columns={columns}
          dataSource={dataSource}
          rowKey={'storeCashFlowCommissionId'}
        />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
      </div>
    );
  }
}

export default Index;
